package service

import (
	"errors"
	"fmt"
	"github.com/mjiulee/lego"
	"github.com/mojocn/base64Captcha"
	"strings"

	. "saas_sys_base/modules/system/models"
)

type SysLoginService struct {
	// add your model here
	tbSysUser  SysUser
	tbLoginLog SysLoginLog
}

func (s *SysLoginService) CheckLoginUser(acc, pwd string) (*SysUser, error) {
	user := s.tbSysUser.RecodeByAccount(acc)
	if user == nil {
		return nil, errors.New("用户不存在")
	}
	// 判断密码
	pwd = s.tbSysUser.EncryptPassword(pwd)
	if 0 != strings.Compare(pwd, user.Password) {
		return nil, errors.New("密码错误")
	}
	return user, nil
}

func (s *SysLoginService) SaveLoginLog(user *SysUser, ip, browser string) bool {
	alog := new(SysLoginLog)
	alog.SysUid = user.Id
	alog.LoginIp = ip
	alog.Browser = browser
	return s.tbLoginLog.AddRecode(alog)
}

func (s *SysLoginService) GetCaptchar() (randstr string, url string) {
	var configC = base64Captcha.ConfigCharacter{
		Height: 60,
		Width:  240,
		//const CaptchaModeNumber:数字,CaptchaModeAlphabet:字母,CaptchaModeArithmetic:算术,CaptchaModeNumberAlphabet:数字字母混合.
		Mode:               base64Captcha.CaptchaModeNumber,
		ComplexOfNoiseText: base64Captcha.CaptchaComplexLower,
		ComplexOfNoiseDot:  base64Captcha.CaptchaComplexLower,
		IsShowHollowLine:   false,
		IsShowNoiseDot:     false,
		IsShowNoiseText:    false,
		IsShowSlimeLine:    false,
		IsShowSineLine:     false,
		CaptchaLen:         6,
	}
	// tempid := uuid.NewV4().String()
	tempid := fmt.Sprintf("%d", lego.UUID())
	captchaId, digitCap := base64Captcha.GenerateCaptcha(tempid, configC)
	base64Png := base64Captcha.CaptchaWriteToBase64Encoding(digitCap)
	return captchaId, base64Png
}
